﻿using SdmxMl.Common;
using SdmxMl.Manager;
using SdmxMl.Multiplexor;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.UI;


namespace SdmxDiff
{
    public partial class DlgVersions : Telerik.WinControls.UI.RadForm
    {
        private const string START_PATTERN = "\\A";
        private const string END_PATTERN = "\\z";

        private ArtefactRefTyped art;

        public string SelectedVersionUrn { get; private set; }

        /// <summary> Dialog for selection of CHOP version </summary>
        public DlgVersions()
        {
            InitializeComponent();
        }

        /// <summary>
        /// From list of Hierarchies, filter targeted ones 
        /// </summary>
        /// <returns>a set containing table with targeted hierarchies</returns>
        public DataSet GetRelatedHierarchies()
        {
            DataSet ds = new DataSet();
            ProxyService reg = Mux.Instance.GetProxyForGroup(art.FullIdent);
            if (reg != null)
            {
                DataSet proxyResult = reg.DirInfo(this.art.Type.ToString());

                // Now filter
                if (proxyResult != null && proxyResult.Tables.Count > 0)
                {
                    DataTable tb = proxyResult.Tables[0].Clone();
                    ds.Tables.Add(tb);
                    foreach (DataRow row in proxyResult.Tables[0].Rows)
                    {
                        if (row["AI"].ToString() == this.art.AgencyId && row["Id"].ToString() == this.art.Id)
                            tb.Rows.Add(row.ItemArray);
                    }
                }
            }
            return ds;
        }
        /// <summary>
        /// Bind all availables versions of CHOP hierarchy in the grid
        /// </summary>
        /// <param name="urnRefArtefact">urn specifying target selection</param>
        public void BindVersionsOf(string urnRefArtefact)
        {
            try
            {
                using (new SdmxMl.Helper.CWaitCursor())
                {
                    art = UrnManager.UrnToArtefactRefTyped(urnRefArtefact);
                    if (art == null)
                        throw new ApplicationException("Invalid reference: " + urnRefArtefact);

                    this.Text = "Versions of Artefact " + art.Id + " of Agency group " + art.AgencyId;

                    ProxyService reg = Mux.Instance.GetProxyForGroup(art.FullIdent);
                    DataSet proxyResult = GetRelatedHierarchies();
                    //DataSet proxyResult = reg.GetArtefactInfos(
                    //    START_PATTERN + art.Type.ToString().ToLower() + END_PATTERN,
                    //    START_PATTERN + art.AgencyId + END_PATTERN,
                    //    START_PATTERN + art.Id + END_PATTERN,
                    //    ".*", DateTime.MinValue, DateTime.MaxValue);

                    if (proxyResult.Tables.Count > 0)
                    {
                        radGridView.BeginUpdate();

                        radGridView.MasterTemplate.Columns.Clear();
                        radGridView.EnableFiltering = false;
                        radGridView.EnableAlternatingRowColor = true;
                        radGridView.MasterTemplate.AllowColumnChooser = false;

                        GridViewTextBoxColumn colText = new GridViewTextBoxColumn("VER");
                        colText.HeaderText = "Version";
                        colText.AllowResize = true;
                        colText.AllowReorder = false;
                        colText.Width = 60;
                        colText.TextAlignment = ContentAlignment.MiddleCenter;
                        radGridView.MasterTemplate.Columns.Add(colText);

                        colText = new GridViewTextBoxColumn("VF");
                        colText.HeaderText = "Valid from";
                        colText.AllowResize = true;
                        colText.AllowReorder = false;
                        colText.Width = 80;
                        colText.TextAlignment = ContentAlignment.MiddleCenter;
                        radGridView.MasterTemplate.Columns.Add(colText);

                        colText = new GridViewTextBoxColumn("VT");
                        colText.HeaderText = "Valid to";
                        colText.AllowResize = true;
                        colText.AllowReorder = false;
                        colText.Width = 80;
                        colText.TextAlignment = ContentAlignment.MiddleCenter;
                        radGridView.MasterTemplate.Columns.Add(colText);


                        colText = new GridViewTextBoxColumn("Name_" + LangSupport.CurLang);
                        colText.HeaderText = "Name";
                        colText.AllowResize = true;
                        colText.AllowReorder = false;
                        colText.Width = 180;
                        radGridView.MasterTemplate.Columns.Add(colText);

                        radGridView.EndUpdate();


                        radGridView.DataSource = proxyResult.Tables[0];
                    }
                }
            }
            catch (Exception ex)
            {
                RadMessageBox.Show(this, ex.Message, "Registry", MessageBoxButtons.OK, RadMessageIcon.Error);
            }

        }

        /// <summary> Selection from grid row event </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void radButtonSelect_Click(object sender, EventArgs e)
        {
            try
            {
                if (art != null && radGridView.CurrentRow != null)
                {
                    ArtefactRefBase arb = new ArtefactRefBase(art.Id, art.AgencyId, radGridView.CurrentRow.Cells["VER"].Value.ToString());
                    SelectedVersionUrn = UrnManager.FullIdToUrn(art.Type, arb.FullIdent);

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                RadMessageBox.Show(this, ex.Message, "Registry", MessageBoxButtons.OK, RadMessageIcon.Error);
            }
        }

        private void radGridView_CellDoubleClick(object sender, GridViewCellEventArgs e)
        {
            radButtonSelect_Click(sender, EventArgs.Empty);

        }
    }
}
